//
//  WeChat.m
//  BrushFace
//
//  Created by timer_q on 15/12/18.
//  Copyright © 2015年 Zzz. All rights reserved.
//

#import "WeChat.h"
#import "WXApi.h"
#import "WXApiObject.h"
#import "AFNetworking.h"
#import "NavHelper.h"
#import "DeviceInfo.h"
#import "MeStatus.h"

#define kWXAccessTokenUrlStr @"https://api.weixin.qq.com/sns/oauth2/access_token"
#define kWXUrlParaAppId         @"appid"
#define kWXUrlParaSecret        @"secret"
#define kWXUrlParaCode          @"code"
#define kWXUrlParaGrantType     @"grant_type"
#define kWXUrlParaGrantTypeKey  @"authorization_code"
@implementation WeChat
{
    AuthRequestCb _saveAuthRqCb;
}
DEF_SINGLETON(WeChat)




#pragma mark - **************** 代理回调 WXApiDelegate
- (void)onReq:(BaseReq *)req{
    //onReq是微信终端向第三方程序发起请求，要求第三方程序响应。第三方程序响应完后必须调用sendRsp返回。在调用sendRsp返回时，会切回到微信终端程序界面。
    
}
- (void)onResp:(BaseResp *)resp{
    
    if ([resp isKindOfClass:[PayResp class]]){
        PayResp*response=(PayResp*)resp;
        switch(response.errCode){
            case WXSuccess:
                //服务器端查询支付通知或查询API返回的结果再提示成功
            {
                NSLog(@"支付成功");
                NSString *payStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"PAY"];
                if ([payStr isEqualToString:@"CHUJIE"]) {
                    [NavHelper gotoBorrowOutSuccess];
                }else if([payStr isEqualToString:@"HUANKUAN"]){
                    [NavHelper gotoHuanKuanSuccess];
                
                }else if([payStr isEqualToString:@"CHONGZHI"]){
                    [NavHelper gotoChongZhiSuccess];
                }
            }
                break;
            default:
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"支付出错啦" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
                NSLog(@"支付失败，retcode=%d",resp.errCode);
            }
                break;
        }
        return;
    }
    //如果第三方程序向微信发送了sendReq的请求，那么onResp会被回调。sendReq请求调用后，会切到微信终端程序界面。
    _loginResp = (SendAuthResp *)resp;
    if (self.loginResp.errCode == WXSuccess)
    {
            _saveAuthRqCb (@"123");
        return;
    }
    else
    {
        return;
    }
}

#pragma mark - **************** 请求

+ (void)sendOrderToWeChatWithPartnerId:(NSString *)partnerId andPrepayId:(NSString *)prepayId andNonceStr:(NSString *)nonceStr andTimeStamp:(NSString *)timeStamp andSign:(NSString *)sign{
    PayReq *request = [[PayReq alloc] init];
    request.partnerId = @"1247121501";//商户id
    request.openID = kWXAppId;
    request.prepayId= [[prepayId componentsSeparatedByString:@"="] lastObject];//预支付订单id
    request.package = @"Sign=WXPay";/** 商家根据财付通文档填写的数据和签名 */
    request.nonceStr= nonceStr;//随机串
    request.timeStamp= [timeStamp intValue];/** 时间戳，防重发 */
    request.sign= sign;/** 商家根据微信开放平台文档对数据做的签名 */
    [WXApi sendReq:request];
}

-(void)sendAuthRequest:(AuthRequestCb)cb
{
    _saveAuthRqCb = [cb copy];
    //构造SendAuthReq结构体
    SendAuthReq* req =[[SendAuthReq alloc ]init];
    req.scope = @"snsapi_userinfo" ;
    req.state = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleNameKey];
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendReq:req];
}

- (void)getAuthAccessTokenCb:(AccessTokenCb)cb
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
    
    NSString * codeStr = [NSString stringWithFormat:@"%@",self.loginResp.code];
    
    @weakify (_accessTokenRsDict);
    [manager GET:kWXAccessTokenUrlStr
      parameters:@{kWXUrlParaAppId:kWXAppId,
                   kWXUrlParaSecret:kWXSecret,
                   kWXUrlParaCode:codeStr,
                   kWXUrlParaGrantType:kWXUrlParaGrantTypeKey}
         success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject)
    {
        @strongify(_accessTokenRsDict);
        NSDictionary * jsonObj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        _accessTokenRsDict = [[NSMutableDictionary alloc]initWithDictionary:jsonObj];
        cb(_accessTokenRsDict);
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        ITLogSP(@"获取accesstoken 失败");
        cb(nil);
    }];
}
@end

@implementation WeChatParseHelper : NSObject
+ (NSString *)getAuthRsAccessToken:(id)rs
{
    NSString * token = nil;
    if ([rs isKindOfClass:[NSDictionary class]])
    {
        token = rs[@"access_token"];
    }
    else
    {
        ITLog(@"参数类型错误");
    }
    return token;
}
@end